SOBJS = start-th.o

COBJS-y += board.o
COBJS-y += clock.o
COBJS-y += $(SOC)_serial.o
COBJS-y += kermit.o
COBJS-y += stdio.o
COBJS-y += th.o
COBJS-y += machine.o
COBJS-y += device.o
COBJS-y += mach-$(BOARD).o

SOBJS-f = $(patsubst %,$(CURDIR)/%,$(SOBJS))
COBJS-f = $(patsubst %,$(CURDIR)/%,$(COBJS-y))
SRCS = $(SOBJS-f:.o=.S) $(COBJS-f:.o=.c)
OBJS = $(SOBJS-f) $(COBJS-f)

DEPS = $(basename $(patsubst %,.depend.%,$(SRCS)))

AFLAGS  += -D__TOP_HALF__
CFLAGS  += -D__TOP_HALF__

.PHONY: all clean depend 

all: $(CURDIR)/mboot-th.bin $(CURDIR)/mboot-th-with-padding.bin

$(CURDIR)/mboot-th.bin: $(CURDIR)/mboot-th.elf
	$(OBJCOPY) $(OBJCFLAGS) -O binary $< $@

$(CURDIR)/mboot-th-with-padding.bin: $(CURDIR)/mboot-th.elf
	$(OBJCOPY) $(OBJCFLAGS) --pad-to=$(CONFIG_SYS_TH_PAD_TO) -O binary $< $@

$(CURDIR)/mboot-th.elf: $(OBJS) $(CURDIR)/mboot-th.lds
	$(LD) $(LDFLAGS) -T $(CURDIR)/mboot-th.lds $(OBJS) -Ttext $(CONFIG_SYS_TH_TEXT_BASE) -Map $(CURDIR)/mboot-th.map -o $@
	$(OBJDUMP) -d $@ > $(CURDIR)/mboot-th.dis

$(CURDIR)/mboot-th.lds:
	rm -f $@
	ln -s $(TOPDIR)/arch/$(ARCH)/kernel/mboot-th.lds $@

$(CURDIR)/start-th.S:
	rm -f $@
	ln -s $(TOPDIR)/arch/$(ARCH)/kernel/start-th.S $@

$(CURDIR)/$(SOC)_serial.c:
	rm -f $@
	ln -s $(TOPDIR)/drivers/serial/$(SOC)_serial.c $@

$(CURDIR)/clock.c:
	rm -f $@
	ln -s $(TOPDIR)/arch/$(ARCH)/$(CPU)/$(SOC)/clock.c $@

$(CURDIR)/machine.c:
	rm -f $@
	ln -s $(TOPDIR)/arch/$(ARCH)/kernel/machine.c $@

$(CURDIR)/mach-$(BOARD).c:
	rm -f $@
	ln -s $(TOPDIR)/arch/$(ARCH)/$(CPU)/$(SOC)/mach-$(BOARD).c $@

$(CURDIR)/device.c:
	rm -f $@
	ln -s $(TOPDIR)/kernel/device.c $@

clean:
	rm -f start-th.S mboot-th.lds clock.c $(SOC)_serial.c machine.c mach-$(BOARD).c device.c
	rm -f *.bin *.elf *.o *.map *.dis
	rm -f .depend*

depend: .depend

.depend: $(DEPS)
	cat $(DEPS) > $@

.depend.%: %.c
	$(CC) $(CFLAGS) -MM $< >$@

.depend.%: %.S
	$(CC) $(ASFLAGS) -MM $< >$@

ifneq ($(MAKECMDGOALS),clean)
sinclude .depend
endif

